package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type WxLoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewWxLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *WxLoginLogic {
	return &WxLoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *WxLoginLogic) WxLogin(req *types.RequestLogin) (resp *types.ResponseLogin, err error) {
	params := url.Values{}
	params.Set("appid", l.svcCtx.Config.WxApp.Appid)
	params.Set("secret", l.svcCtx.Config.WxApp.Secret)
	params.Set("js_code", req.Code)
	params.Set("grant_type", "authorization_code")
	uri := l.svcCtx.Config.WxApp.LoginUri + "?" + params.Encode()
	// 发起GET请求
	res, err := http.Get(uri)
	if err != nil {
		logx.Error("微信登录请求失败:", err)
		return
	}
	defer res.Body.Close()
	//// 读取响应内容
	body, err := io.ReadAll(res.Body)
	if err != nil {
		logx.Error("微信登录读取响应失败:", err)
		return
	}
	var response WeChatLoginResponse
	err = json.Unmarshal(body, &response)
	if err != nil {
		logx.Error("微信登录响应体请求解析失败:", err)
		return nil, err
	}
	fmt.Println(response)
	return &types.ResponseLogin{
		OpenId: response.OpenID,
		Msg:    "登录成功",
		Code:   200,
	}, nil
}
